﻿<?php

/**
 * 类
 */
class Paypal extends BaseModel
{
    /**
     * 构造函数
     *
     * @access  public
     * @param
     *
     * @return void
     */
    function paypal()
    {
    }

    function __construct()
    {
        $this->paypal();
    }

    /**
     * 生成支付代码
     * @param   array   $order  订单信息
     * @param   array   $payment    支付方式信息
     */
    function payTo($payment,$returnurl,$pay)
    {
        $data_order_id      = $pay['orderid'];
        $data_amount        = $pay['price'];
        $data_return_url    = $returnurl;
        $data_pay_account   = $payment['paypal_account'];
        $currency_code      = $payment['paypal_currency'];
        $data_notify_url    = $returnurl;

        $def_url  = '<br /><form style="text-align:center;" action="https://www.paypal.com/cgi-bin/webscr" method="post">' .   // 不能省略
            "<input type='hidden' name='cmd' value='_xclick'>" .                             // 不能省略
            "<input type='hidden' name='business' value='$data_pay_account'>" .                 // 贝宝帐号
            "<input type='hidden' name='return' value='$data_return_url'>" .                    // 付款后页面
            "<input type='hidden' name='amount' value='$data_amount'>" .                        // 订单金额
            "<input type='hidden' name='invoice' value='$data_order_id'>" .                      // 订单号
            "<input type='hidden' name='charset' value='utf-8'>" .                              // 字符集
            "<input type='hidden' name='no_shipping' value='1'>" .                              // 不要求客户提供收货地址
            "<input type='hidden' name='no_note' value=''>" .                                  // 付款说明
            "<input type='hidden' name='currency_code' value='$currency_code'>" .            // 货币，定义币种以标示货币变量 值可以为 "USD"、"EUR"、"GBP"、"CAD"、"JPY"。 

            "<input type='hidden' name='notify_url' value='$data_notify_url'>" .
            "<input type='hidden' name='item_name' value='".$pay['name']."'>" .                 // 物品名称（或购物车名称）。必须是字母数字字符，最多为 127 个字符
            "<input type='submit' value='" .立即使用贝宝进行支付. "'>" .                      // 按钮
            "</form><br />";

        return $def_url;
    }

    /**
     * 响应操作
     */
    function dopayRe()
    {
        // read the post from PayPal system and add 'cmd'
        $req = 'cmd=_notify-validate';
        foreach ($_POST as $key => $value)
        {
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
        }

		$sql='select * from '.$this->_prefix.'shoporderuser where id  = '.addslashes($_POST['invoice']);
	    $order=$this->db->get_one($sql);

	   if($order['id']=='')return "无法继续付款，无法找到订单!";
	   if($order['ifpay']==1)return "请勿重复使用已支付的订单!";
		
	   $sql='select * from '.$this->_prefix.'payment where pay_code   =\''.addslashes($_GET['pay']).'\'';
	   $pay=$this->db->get_one($sql);
	   $payment=unserialize($pay['pay_config']);	
       $merchant_id    = $payment['paypal_account'];               ///获取商户编号
		
        // post back to PayPal system to validate
        $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($req) ."\r\n\r\n";
        $fp = fsockopen ('ssl://www.paypal.com',443, $errno, $errstr, 30);

        // assign posted variables to local variables
        $item_name = $_POST['item_name'];
        $item_number = $_POST['item_number'];
        $payment_status = $_POST['payment_status'];
        $payment_amount = $_POST['mc_gross'];
        $payment_currency = $_POST['mc_currency'];
        $txn_id = $_POST['txn_id'];
        $receiver_email = $_POST['receiver_email'];
        $payer_email = $_POST['payer_email'];
        $order_sn = $_POST['invoice'];
        $action_note = $txn_id . '（' .paypal交易号. '）' . $_POST['memo'];

        if (!$fp)
        {
            fclose($fp);

            return false;
        }
        else
        {
            fputs($fp, $header . $req);
            while (!feof($fp))
            {
                $res = fgets($fp, 1024);
                if (strcmp($res, 'VERIFIED') == 0)
                {
                    // check the payment_status is Completed
                    if ($payment_status != 'Completed')
                    {
                        fclose($fp);
                        return false;
                    }

					
					if ($receiver_email != $merchant_id)
                    {
                        fclose($fp);
                        return false;
                    }
	
                    fclose($fp);
		            return $ary=array('price'=> $payment_amount ,'orderid'=>$order_sn);
                }
                elseif (strcmp($res, 'INVALID') == 0)
                {
                    // log for manual investigation
                    fclose($fp);

                    return false;
                }
            }
        }
    }
}

?>